package com.examination.client.redis.impl;

import com.examination.client.redis.RedisDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 *  redis实现类
 * Created by liangtao on 2020/3/11
 */
@Repository
public class RedisDaoImpl implements RedisDao {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean hasKeyAndValue(String key, String value) {
        return stringRedisTemplate.opsForValue().setIfAbsent(key, value);
    }

    @Override
    public void setExpire(String key, long timeOut, TimeUnit timeUnit) {
        stringRedisTemplate.expire(key, timeOut, timeUnit);
    }

    @Override
    public String getValue(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }

    @Override
    public void setKeyValue(String key, String value, int timeOut, TimeUnit timeUnit) {
        stringRedisTemplate.opsForValue().set(key, value, timeOut, timeUnit);
    }

    @Override
    public void setHashMap(String key, Map<String, Object> map) {
        stringRedisTemplate.opsForHash().putAll(key, map);
    }

    @Override
    public boolean hasKey(String key) {
        return stringRedisTemplate.hasKey(key);
    }

    @Override
    public Object getHashMapValue(String rkey, String mkey) {
        return  stringRedisTemplate.opsForHash().get(rkey, mkey);
    }

    @Override
    public boolean hasHashMapKey(String rkey, String mkey) {
        return stringRedisTemplate.opsForHash().hasKey(rkey, mkey);
    }

    @Override
    public void setHashList(String key, List<String> list) {
        stringRedisTemplate.opsForList().leftPushAll(key, list);
    }

    @Override
    public void setHashListValue(String key, String value) {
        stringRedisTemplate.opsForList().leftPush(key, value);
    }

    @Override
    public List<String> getHashList(String key) {
        return stringRedisTemplate.opsForList().range(key, 0, -1);
    }

    @Override
    public void deleteKey(String key) throws Exception {
        try {
            if (stringRedisTemplate.hasKey(key)) {
                stringRedisTemplate.delete(key);
            }
        } catch (Exception e) {
                throw new Exception("delete redis key fail");
        }
    }
}
